$(document).ready(function() {
	SB.PhotoModel = Backbone.Model.extend({});
	SB.selectedPhotos = {};

	SB.PhotoView = Backbone.View.extend({
		className : "center-box share-photo",

		template : _.template($('#photo-tpl').html()),

		events : {
			'click img' : "toggleSelection"
		},

		render : function() {
			$(this.el).html(this.template(this.model.toJSON()));
			return this;
		},

		toggleSelection : function() {
			console.log('toggleSelection');
			// Update UI
			$(this.el).toggleClass('photo-selected');
			
			// Update selected photos
			var index = this.model.get('index');
			if (index in SB.selectedPhotos) {
				delete (SB.selectedPhotos[index]);
			} else {
				SB.selectedPhotos[index] = this.model.get('src');
			}
			console.log(SB.selectedPhotos);
		}
	});

	SB.ShareLinkPopupView = Backbone.View.extend({
		className : "share-link span11",

		initialize : function() {
			_.bindAll(this, 'render');
		},
		
		events: {
			'click #share-link-submit' : "submitLink"			
		},

		template : _.template($('#share-link-tpl').html()),

		render : function() {
			var $this = this;
			$(this.el).html(this.template());

			$.each(this.options.photoUrls, function(index, url) {
				var photo = new SB.PhotoModel();
				photo.set({
					'src' : url,
					'index' : index
				});
				var photoView = new SB.PhotoView({
					model : photo
				});
				$this.$('.photos').append(photoView.render().el);
			});

			// Remove small photo and doing resizing
			this.$('.photos').imagesLoaded(function($images, $proper, $broken) {
				//$proper = $('img');
				console.log($proper.width() + "--" + $proper.height());
				console.log($proper);
				$.each($proper, function(i, img) {
					$img = $(img);
					console.log($img.width() + "--" + $img.height());
					if ($img.width() < 200 || $img.height() < 150) {
						$img.parent().remove();
					} else if ($img.width() > $img.height()) {
						$img.css('height', '100%');
						$img.css('width', 'auto');
					} else {
						$img.css('height', 'auto');
						$img.css('width', '100%');
					}
				});
				$broken.parent().remove();
			});

			return this;
		},
		
		submitLink : function() {
			var params = params || {};
			params.url = this.options.url;
			params.title = this.options.title;
			params.note = this.$('#share-link-note').val();

			params.photos = [];
			for (key in SB.selectedPhotos) {
				params.photos.push(SB.selectedPhotos[key]);
			}
			params.photos = JSON.stringify(params.photos);
			$.post('/api/article/create/', params, function(data) {
				$('#share-link-input').val('');
				$.fancybox.close();
			});
		}

	});
});
